from browser import document
from browser import ajax
from browser import alert
from browser import window
import json

inputHostAddr = document["inputHostAddr"]
inputHostUsername = document["inputHostUsername"]
inputHostPasswd = document["inputHostPasswd"]
inputHostIdentity = document["inputHostIdentity"]
inputHostRemask = document["inputHostRemask"]
saveHostsInfo = document["saveHostsInfo"]

fromdata = document.baseURI.split("?")[1]

dataItem = {}
optionChecked = {}

for item in fromdata.split("&"):
    k = item.split("=")[0]
    v = item.split("=")[1]

    dataItem[k] = v

def queryHostInfo(req):
    if req.status == 200:
        data = json.loads(req.text)
        inputHostAddr.value = data["Data"][0]["Addr"]
        inputHostUsername.value = data["Data"][0]["Username"]
        inputHostRemask.value = data["Data"][0]["Remask"]


request = ajax.Ajax()
request.bind("complete", queryHostInfo)
request.open("GET", "/showHosts?id="+dataItem["id"], False)
request.send()

def addHostDatas(req):
    alert(req.text)
    window.location.href = "./index.html?page=hosts"

def saveHosts(ev):
    reqData = {
        "id": str(dataItem["id"]),
        "addr": inputHostAddr.value,
        "hostname": inputHostUsername.value,
        "password": inputHostPasswd.value,
        "identity": inputHostIdentity.value,
        "remask": inputHostRemask.value
    }

    request = ajax.Ajax()
    request.bind("complete", addHostDatas)
    request.open("POST", "/manageHosts", False)
    request.send(reqData)

saveHostsInfo.bind("click",saveHosts)